<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>使用Promise封装原生Ajax</title>
    </head>
    <body>
        <h2>该页面是测试使用Promise封装原生Ajax</h2>
        <button id="btn">点我, 发送GET请求</button>
        <button id="btn2">点我, 发送POST请求</button>
        <div id="div"></div>
        
        <script type="text/javascript">
            function sendAjax(url, method, data){
                return new Promise((resolve, reject) => {
                    // 1. 创建xhr对象
                    let xhr = new XMLHttpRequest()
                    // 2. 绑定监听
                    xhr.onreadystatechange = function(){
                        if(xhr.readyState != 4){
                            return;
                        }
                        if(xhr.readyState == 4 && (xhr.status >=200 || xhr.status <=299)){
                            const responseObj = {
                                data: xhr.response,
                                status: xhr.status,
                                statusText: xhr.statusText
                            }
                            resolve(responseObj)
                        }else{
                            reject(new Error("请求出错了"))
                        }
                    }
                    // 3. 设置请求的方式, 地址, 携带的参数
                    let dataKeys = Object.keys(data)
                    // 4. 将传递过来的数据对象加工成urlencoded形式的编码
                    let str = dataKeys.reduce(function(pre, now){
                        return pre+=`${now}=${data[now]}&`
                    },"")
                    // 5. 发送请求
                    if(method.toLowerCase() === "get"){
                        url += `?${str}`
                        xhr.open(method, url)
                        xhr.send()
                    }else if(method.toLowerCase() === "post"){
                        xhr.open(method, url)
                        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded")
                        xhr.send(str)
                    }
                }) 
            }
            
            document.getElementById("btn").onclick = function(){
                sendAjax("http://localhost:3000/test_get", "get", {name: "kobe", age: 18})
                    .then((data) => {
                        console.log(data)
                    }).catch((err) => {
                        console.log(err)
                    })
            }

            document.getElementById("btn2").onclick = function(){
                sendAjax("http://localhost:3000/test_post", "post", {name: "kobe", age: 18})
                    .then((data) => {
                        console.log(data)
                    }).catch((err) => {
                        console.log(err)
                    })
            }
        </script>
    </body>
</html>